package com.yljk.yljkproject.ui.webview;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.shicheng.alerts.AlertDialogManager;
import com.shicheng.alerts.callback.AlertDialogimpl;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.BitmapUtils;
import com.yljk.mcbase.utils.utilcode.util.ActivityUtils;

/**
 * Create By shicheng
 *
 * 原生web页提供js方法实现
 * Android web page (WebView) provide js function
 *
 */
public class WebJavascriptInterface {

    private Context context;
    private Activity activity;
    public WebJavascriptInterface(Context context) {
        this.context = context;
        activity = (Activity) context;
    }


    /**
     * 图片长按
     *
     * @param src 图片的链接
     */
    @JavascriptInterface
    public void imageLongClick(String src) {
        Toast.makeText(context, "图片长按", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片长按
     *
     */
    @JavascriptInterface
    public void imageLongClick() {
        Toast.makeText(context, "图片长按", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片点击
     *
     * @param src 图片的链接
     */
    @JavascriptInterface
    public void imageClick(String src) {
        Toast.makeText(context, "图片点击", Toast.LENGTH_SHORT).show();
    }

    /**
     * 图片保存
     *
     * @param src 图片的链接
     */


    @JavascriptInterface
    public void saveImage(String src) {
        AlertDialogManager.builder()
                .setContext(activity)
                .setType(1)
                .setNegativeButton("取消")
                .setBottomLists(new String[]{"保存"})
                .setBottomItemCallback(new AlertDialogimpl() {
                    @Override
                    public void Success(int i, String s) {
                        super.Success(i, s);
//                        Toast.makeText(activity, i+"==="+s, Toast.LENGTH_SHORT).show();
                        if (i == 0){
                            Bitmap bitmap = null;
                            if (src.startsWith("http")) {
                                bitmap = BitmapUtils.GetImageInputStream(src);
                            } else {
                                bitmap = BitmapUtils.base64ToBitmap(src.substring(src.indexOf(",") + 1));
                            }
                            if (bitmap == null) {
                                ALog.i(this.getClass().getName(), "bitmap is null");
                            } else {
//            BitmapUtils.saveBitmap(bitmap, imagePath);
                                BitmapUtils.saveImageToGallery(activity, bitmap);
                                Toast.makeText(ActivityUtils.getTopActivity(), "图片保存成功", Toast.LENGTH_SHORT).show();
                                AlertDialogManager.dismiss();
                            }
                        }
                    }
                })
                .show();
    }


}
